﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using SuperSocket.ClientEngine;
using System;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using ErrorEventArgs = SuperSocket.ClientEngine.ErrorEventArgs;
using Timer = System.Timers.Timer;

namespace Simple.Services.Socket
{
    public class SocketClientServer
    {
        private AsyncTcpSession _tcpClient;
        private readonly ILogger _logger;
        private readonly IConfiguration _configuration;
        private Timer _timer;
        private IPAddress _ipAddress;
        private int _port;

        public SocketClientServer(ILogger<SocketClientServer> logger, IConfiguration configuration)
        {
            _logger = logger;
            _configuration = configuration;
        }

        public void StartClient()
        {
            try
            {
                //var serverInfo = _configuration["SocketServer"];
                //var infos = serverInfo.Split(';');
                var ip = "140.246.101.8";
                var port = "8190";
                _ipAddress = IPAddress.Parse(ip);
                _port = int.Parse(port);
                _tcpClient = new AsyncTcpSession();
                _tcpClient.Connected += OnClientConnected;
                _tcpClient.Error += OnClientError;
                _tcpClient.Closed += OnClientClosed;
                _tcpClient.DataReceived += client_DataReceived;
                _tcpClient.Connect(new IPEndPoint(_ipAddress, _port));
                //每20s发送一次心跳或尝试一次重连
                _timer = new Timer(20000);
                _timer.Elapsed += new ElapsedEventHandler((s, x) =>
                {
                    if (_tcpClient.IsConnected)
                    {
                        // 暂不需要心跳
                    }
                    else if (!_tcpClient.IsConnected)
                    {
                        _tcpClient.Connect(new IPEndPoint(_ipAddress, _port));
                    }
                });
                _timer.Enabled = true;
                _timer.Start();

                _logger.LogError($"StoppedAsync：MQTT服务已关闭……");

            }
            catch (Exception ex)
            {
                _logger.LogInformation(ex, $"连接Socket服务端失败，IP:{_ipAddress?.ToString()},端口:{_port}");
            }
        }
        private void OnClientConnected(object sender, EventArgs e)
        {
            _logger.LogInformation($"连接Socket服务端成功，IP:{_ipAddress?.ToString()},端口:{_port}");
        }
        private void OnClientClosed(object sender, EventArgs e)
        {
            _logger.LogInformation($"与Socket服务已断开，IP:{_ipAddress?.ToString()},端口:{_port}");
        }
        private void OnClientError(object sender, ErrorEventArgs e)
        {
            _logger.LogInformation(exception: e.Exception, $"SocketClientServer发生错误，IP:{_ipAddress?.ToString()},端口:{_port}");
        }
        private void client_DataReceived(object sender, DataEventArgs e)
        {
            // 暂不接收服务端发送的消息
            string msg = Encoding.Default.GetString(e.Data);
        }

        public async Task SendDeviceMessageAsync(string message)
        {
            _tcpClient.Send(Encoding.UTF8.GetBytes("Device " + message + "\r\n"));
            await Task.CompletedTask;
        }

        public async Task SendDeviceLoginAsync(string deviceId)
        {
            _tcpClient.Send(Encoding.UTF8.GetBytes("DeviceLogin " + deviceId + "\r\n"));
            await Task.CompletedTask;
        }
    }
}
